package com.rg1906.utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceC3P0ThreadLocal { 
	// 通过读取配置文件静态创建dataSource连接池
	private static DataSource dataSource = new ComboPooledDataSource("mysql");
	private static Connection conn = null;
	// 线程绑定Connection对象
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	// 回滚事务
	public static void rollback() throws SQLException {
		// 获取与当前线程绑定的Connection对象
		conn = getCurrentConnection();
		// 回滚事务
		conn.rollback();
		// 将线程上绑定的Connection对象移除
		tl.remove();
		// 关闭连接
		conn.close();

	}
	// 提交事务
	public static void commit() throws SQLException {
		// 获取与当前线程绑定的Connection对象
		conn = getCurrentConnection();
		// 提交事务
		conn.commit();
		// 将线程上绑定的Connection对象移除
		tl.remove();
		// 关闭连接
		conn.close();
	}

	// 开启事务
	public static void startTransaction() throws SQLException {
		// 获取与当前线程绑定的Connection对象
		conn = getCurrentConnection();
		// 设置线程自动提交失效(开启事务)
		conn.setAutoCommit(false);
	}

	// 返回当前线程绑定的Connection对象
	public static Connection getCurrentConnection() throws SQLException {
		// 获取当前线程绑定的Connection对象
		conn = tl.get();
		// 对获取的Connection对象进行判断
		if (conn == null) {
			// 如果当前线程未绑定Connection对象则调用方法创建Connection对象
			conn = getConnection();
			// 创建完Connection对象将其与当前线程绑定
			tl.set(conn);
		}
		// 返回当前线程绑定的Connection对象
		return conn;
	}

	// 返回连接池
	public static DataSource getDataSource() {
		return dataSource;
	}

	// 返回Connection对象
	public static Connection getConnection() throws SQLException {
		conn = dataSource.getConnection();
		return conn;
	}
}
